package cn.zhoushengdao.bingwallpaper

import android.app.WallpaperManager
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Quiz
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Wallpaper
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ModalBottomSheetProperties
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TooltipBox
import androidx.compose.material3.TooltipDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTooltipState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.lerp
import androidx.core.net.toUri
import cn.zhoushengdao.bingwallpaper.ui.theme.BingWallpaperTheme
import coil3.compose.AsyncImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.URL
import kotlin.math.absoluteValue

class MainActivity : ComponentActivity() {
    private val data by lazy { AppData(this) }
    private val repository by lazy { WallpaperRepository(this, data) }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        enableEdgeToEdge()

        setContent {
//            val context = LocalContext.current
//
//            val data = remember(context) {
//                AppData(context.applicationContext)
//            }
//
//
//
//            LaunchedEffect(Unit) {
//                val windowMetrics = windowManager.currentWindowMetrics
//                val bounds = windowMetrics.bounds
//                val screenWidth = bounds.width()
//                val screenHeight = bounds.height()
//                wallpaperViewModel.setScreenSize(screenWidth, screenHeight)
//            }

            BingWallpaperTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {
                    WallpaperApp(data, repository)
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WallpaperApp(data: AppData, repository: WallpaperRepository) {
    val context = LocalContext.current

    val autoChangeEnabled by data.autoChangeEnabled.collectAsState(initial = AppData.DEFAULT_AUTO_CHANGE)
    val currentWallpaperUrl by data.currentWallpaperUrl.collectAsState(initial = "")
    val currentLocale by data.currentLocale.collectAsState(initial = AppData.DEFAULT_LOCALE)
    val wallpapers by data.wallpapers.collectAsState(emptyList())

    val coroutineScope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }
    val wallpaperManager by lazy { WallpaperManager.getInstance(context) }
    var localeMenuExpanded by remember { mutableStateOf(false) }
    var showDetailSheet by remember { mutableStateOf(false) }

    val localeToRString = mapOf(
        "de-DE" to R.string.locale_deDE,
        "en-CA" to R.string.locale_enCA,
        "en-GB" to R.string.locale_enGB,
        "en-IN" to R.string.locale_enIN,
        "en-US" to R.string.locale_enUS,
        "es-ES" to R.string.locale_esES,
        "fr-CA" to R.string.locale_frCA,
        "fr-FR" to R.string.locale_frFR,
        "it-IT" to R.string.locale_itIT,
        "ja-JP" to R.string.locale_jaJP,
        "pt-BR" to R.string.locale_ptBR,
        "zh-CN" to R.string.locale_zhCN,
    )


    // 壁纸设置结果处理
//    LaunchedEffect(wallpaperViewModel.setWallpaperResult.value) {
//        wallpaperViewModel.setWallpaperResult.value?.let { result ->
//            if (result) {
//                snackbarHostState.showSnackbar("壁纸设置成功!")
//            } else {
//                snackbarHostState.showSnackbar("壁纸设置失败，请重试")
//            }
//            wallpaperViewModel.clearSetWallpaperResult()
//        }
//    }

    Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = {
        TopAppBar(title = {
            Row(verticalAlignment = Alignment.CenterVertically) {
                // 区域选择下拉菜单
                Box {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .clickable { localeMenuExpanded = true }
                            .padding(end = 16.dp)) {
                        Text(
                            text = stringResource(
                                localeToRString[currentLocale] ?: R.string.locale_zhCN
                            ),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Icon(
                            imageVector = Icons.Default.ArrowDropDown,
                            contentDescription = "选择区域"
                        )
                    }

                    // 区域选择菜单
                    DropdownMenu(
                        expanded = localeMenuExpanded,
                        onDismissRequest = { localeMenuExpanded = false }) {
                        localeToRString.keys.forEach { locale ->
                            DropdownMenuItem(
                                text = { Text(stringResource(localeToRString[locale]!!)) },
                                onClick = {
                                    localeMenuExpanded = false
                                    coroutineScope.launch {
                                        data.setCurrentLocale(locale)
                                        data.setWallpapers(repository.fetchWallpapers())
                                    }
                                })
                        }
                    }
                }
            }
        }, actions = {
            // 自动更新开关
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    "自动更新",
                    style = MaterialTheme.typography.labelLarge,
                    modifier = Modifier.padding(end = 8.dp)
                )
                Switch(
                    checked = autoChangeEnabled, onCheckedChange = { enabled ->
                        coroutineScope.launch {
                            data.setAutoChangeEnabled(enabled)
                            if (enabled) {
                                // scheduleAutoWallpaperWorker(context) // TODO
                                snackbarHostState.showSnackbar("已开启自动更新")
                            } else {
                                // cancelAutoWallpaperWorker(context) // TODO
                                snackbarHostState.showSnackbar("已关闭自动更新")
                            }
                        }
                    })
            }

            // 刷新按钮
            TooltipBox(
                positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                tooltip = { Text(stringResource(R.string.refresh)) },
                state = rememberTooltipState(),
            ) {
                IconButton(
                    onClick = {
                        coroutineScope.launch {
                            data.setWallpapers(repository.fetchWallpapers())
                            data.debugPrint()
                        }
                    },
                    modifier = Modifier,
                ) {
                    Icon(
                        Icons.Default.Refresh, contentDescription = stringResource(R.string.refresh)
                    )
                }
            }
        })
    }) { innerPadding ->
        Box(
            modifier = Modifier
                .padding(innerPadding)
                .fillMaxSize()
        ) {
            if (wallpapers.isEmpty()) {
                LaunchedEffect(Unit) { data.setWallpapers(repository.fetchWallpapers()) }
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(64.dp), color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Text("没有壁纸数据", fontSize = 24.sp)
                }
            } else {
                // 创建轮播状态
                val pagerState = rememberPagerState(
                    initialPage = 0,
                    initialPageOffsetFraction = 0f,
                    pageCount = { wallpapers.size })

                // 进入应用时滚动到当前壁纸或第一张壁纸
                LaunchedEffect(wallpapers) {
                    if (wallpapers.isNotEmpty()) {
                        val index = wallpapers.indexOfFirst { it.imageUrl == currentWallpaperUrl }
                        pagerState.scrollToPage(if (index >= 0) index else 0)
                    }
                }

                // 轮播区域
                HorizontalPager(
                    state = pagerState, modifier = Modifier.fillMaxSize()
                ) { pageIndex ->
                    // 计算缩放效果
                    val pageOffset =
                        (pagerState.currentPage - pageIndex) + pagerState.currentPageOffsetFraction
                    val scaleFactor = lerp(
                        start = 0.85f, stop = 1f, fraction = 1f - pageOffset.absoluteValue
                    )

                    // 壁纸项目
                    val wallpaper = wallpapers[pageIndex]
                    WallpaperCard(
                        wallpaper = wallpaper, modifier = Modifier
                            .graphicsLayer {
                                scaleX = scaleFactor
                                scaleY = scaleFactor
                                alpha = scaleFactor
                            }
                            .fillMaxSize(), onClick = {
                            showDetailSheet = true
                        }, onLongClick = {
                            Toast.makeText(context, "设为壁纸中……", Toast.LENGTH_SHORT).show()

                            coroutineScope.launch {
                                withContext(Dispatchers.IO) {
                                    val metrics = context.resources.displayMetrics
                                    val fullUrl = wallpaper.getFullImageUrl(
                                        metrics.widthPixels, metrics.heightPixels
                                    )
                                    URL(fullUrl).openStream().use { wallpaperManager.setStream(it) }
                                    data.setCurrentWallpaperUrl(wallpaper.imageUrl)

                                    withContext(Dispatchers.Main) {
                                        snackbarHostState.showSnackbar("壁纸设置成功!")
                                    }
                                }
                            }
                        })
                }

                if (showDetailSheet) {
                    ModalBottomSheet(
                        onDismissRequest = { showDetailSheet = false },
                        sheetState = rememberModalBottomSheetState(),
                        properties = ModalBottomSheetProperties(shouldDismissOnBackPress = true)
                    ) {
                        WallpaperDetailDrawer(
                            wallpaper = wallpapers[pagerState.currentPage],
                            isCurrentWallpaper = wallpapers[pagerState.currentPage].imageUrl == currentWallpaperUrl,
                            onDismiss = { showDetailSheet = false },
                            onSetWallpaper = {
                                val wallpaper = wallpapers[pagerState.currentPage]

                                coroutineScope.launch {
                                    withContext(Dispatchers.IO) {
                                        val metrics = context.resources.displayMetrics
                                        val fullUrl = wallpaper.getFullImageUrl(
                                            metrics.widthPixels, metrics.heightPixels
                                        )
                                        URL(fullUrl).openStream()
                                            .use { wallpaperManager.setStream(it) }
                                        data.setCurrentWallpaperUrl(wallpaper.imageUrl)

                                        withContext(Dispatchers.Main) {
                                            showDetailSheet = false
                                            snackbarHostState.showSnackbar("壁纸设置成功!")
                                        }
                                    }
                                }
                            })
                    }
                }
            }
        }
    }
}

@Composable
fun WallpaperCard(
    wallpaper: WallpaperData,
    modifier: Modifier = Modifier,
    onClick: () -> Unit,
    onLongClick: () -> Unit
) {
    val context = LocalContext.current

    Box(
        modifier = modifier.combinedClickable(
            onClick = onClick, onLongClick = onLongClick, onLongClickLabel = "设为壁纸"
        )
    ) {
        // 生成完整图片URL
        val metrics = context.resources.displayMetrics
        val imageUrl = wallpaper.getFullImageUrl(metrics.widthPixels, metrics.heightPixels)

        // 壁纸图像
        AsyncImage(
            model = imageUrl,
            contentDescription = wallpaper.title,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize(),
        )

        // 标题区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.Black.copy(alpha = 0.5f))
                .align(Alignment.BottomCenter)
                .padding(16.dp)
        ) {
            Text(
                text = wallpaper.headline,
                color = Color.White,
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WallpaperDetailDrawer(
    wallpaper: WallpaperData?,
    isCurrentWallpaper: Boolean,
    onDismiss: () -> Unit,
    onSetWallpaper: () -> Unit,
) {
    val context = LocalContext.current

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp)
            .verticalScroll(rememberScrollState())
    ) {
        wallpaper?.let { wp ->
            // 标题区域
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = wp.title,
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f)
                )

                // 关闭按钮
                Box(
                    modifier = Modifier.padding(start = 8.dp)
                ) {
                    TooltipBox(
                        positionProvider = TooltipDefaults.rememberRichTooltipPositionProvider(),
                        tooltip = { Text("关闭") },
                        state = rememberTooltipState()
                    ) {
                        IconButton(
                            onClick = onDismiss, modifier = Modifier
                        ) {
                            Icon(
                                imageVector = Icons.Default.Close, contentDescription = "关闭"
                            )
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 设为壁纸按钮
            Button(
                onClick = onSetWallpaper,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp)
                    .height(52.dp),
                shape = RoundedCornerShape(12.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                ),
                enabled = !isCurrentWallpaper
            ) {
                Icon(
                    Icons.Default.Wallpaper,
                    contentDescription = if (isCurrentWallpaper) "当前壁纸" else "设为壁纸"
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = if (isCurrentWallpaper) "当前壁纸" else "设为壁纸",
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 日期
            Text(
                text = wp.date,
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),
                modifier = Modifier.padding(horizontal = 24.dp)
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 版权信息
            Text(
                text = wp.copyright,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),
                modifier = Modifier.padding(horizontal = 24.dp)
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 关键信息卡片
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                shape = RoundedCornerShape(16.dp),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceContainer
                )
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = wp.headline,
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )

                    Spacer(modifier = Modifier.height(12.dp))

                    Text(
                        text = wp.description,
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurface
                    )

                    // 地图预览
                    if (wp.mapImage.isNotBlank()) {
                        Spacer(modifier = Modifier.height(12.dp))

                        AsyncImage(
                            model = wp.mapImage,
                            contentDescription = "地图预览",
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(8.dp))
                                .clickable {
                                    if (wp.mapUrl.isNotBlank()) {
                                        context.startActivity(
                                            Intent(
                                                Intent.ACTION_VIEW, wp.mapUrl.toUri()
                                            )
                                        )
                                    }
                                },
                            contentScale = ContentScale.Crop
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 底部动作按钮区域
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp)
                    .padding(bottom = 24.dp), horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 详细信息按钮
                if (wp.quizUrl.isNotBlank()) {
                    Button(
                        onClick = {
                            context.startActivity(Intent(Intent.ACTION_VIEW, wp.searchUrl.toUri()))
                        },
                        modifier = Modifier.weight(1f),
                        shape = RoundedCornerShape(12.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Icon(Icons.Default.Search, contentDescription = "详细信息")
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(text = "详细信息", fontWeight = FontWeight.Bold)
                    }

                    Spacer(modifier = Modifier.width(16.dp))
                }

                // 参加测验按钮
                if (wp.searchUrl.isNotBlank()) {
                    OutlinedButton(
                        onClick = {
                            context.startActivity(Intent(Intent.ACTION_VIEW, wp.quizUrl.toUri()))
                        },
                        modifier = Modifier.weight(1f),
                        shape = RoundedCornerShape(12.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Icon(Icons.Default.Quiz, contentDescription = "参加测验")
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(text = "参加测验", fontWeight = FontWeight.Bold)
                    }
                }
            }
        } ?: run {
            // 加载状态
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .padding(40.dp),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }
    }
}
